package com.speciality.demo.demos.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.speciality.demo.demos.dto.TravelAdviceDTO;
import com.speciality.demo.demos.service.TravelAdviceService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.spark.sql.SparkSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import static org.apache.logging.log4j.message.MapMessage.MapFormat.JSON;

@Slf4j
@Service
public class TravelAdviceServiceImpl implements TravelAdviceService {


    private volatile SparkSession sparkSession;

    private void initializeSpark() {
        if (sparkSession == null) {
            synchronized (this) {  // 双重检查锁保证线程安全
                if (sparkSession == null) {
                    sparkSession = SparkSession.builder()
                            .appName("AgriculturalAnalysis")
                            .master("local[*]")
                            .config("spark.driver.memory", "4g")
                            .config("spark.sql.adaptive.enabled", "true")
                            .getOrCreate();
                    log.info("Spark会话初始化完成");
                }
            }
        }
    }


    // 哈尔滨天气接口（编码 101050101 对应哈尔滨）
    private static final String WEATHER_API = "http://t.weather.itboy.net/api/weather/city/101050101";

    public TravelAdviceDTO getHarbinFormalAdvice() throws IOException {
        // 1. 调用接口获取数据
        String weatherJson = callWeatherApi();
        TravelAdviceDTO adviceDTO = com.alibaba.fastjson.JSON.parseObject(weatherJson, TravelAdviceDTO.class);

        // 2. 处理7天预报，生成严肃建议
        LocalDate currentDate = LocalDate.parse(adviceDTO.getTime().substring(0, 10));
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (TravelAdviceDTO.Forecast forecast : adviceDTO.getData().getForecast()) {
            // 补全完整日期逻辑（若需更严谨可结合接口返回的ymd）
            LocalDate forecastDate = currentDate.plusDays(
                    adviceDTO.getData().getForecast().indexOf(forecast)
            );
            forecast.setYmd(forecastDate.format(formatter));
            // 生成严肃版建议
            forecast.setFormalAdvice(generateFormalAdvice(forecast));
        }

        return adviceDTO;
    }

    private String callWeatherApi() throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(WEATHER_API)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("接口调用失败: " + response);
            }
            return response.body().string();
        }
    }

    private String generateFormalAdvice(TravelAdviceDTO.Forecast forecast) {
        StringBuilder advice = new StringBuilder();
        advice.append("【日期】").append(forecast.getYmd()).append("（").append(forecast.getWeek()).append("）\n")
                .append("【天气】").append(forecast.getType()).append("，").append(forecast.getLow()).append("~").append(forecast.getHigh()).append("\n")
                .append("【风险提示】");

        if (forecast.getType().contains("雨")) {
            advice.append("降水易致道路湿滑、能见度降低，存在交通事故隐患；户外作业需暂停高空、涉水作业，配备防滑装备。\n")
                    .append("【通勤规范】公共交通建议提前规划，预计有5 - 10分钟延误；驾车需保持≥50米安全车距，时速≤40km/h。\n")
                    .append("【健康防护】避免长时间淋雨，预防低体温症；过敏人群佩戴口罩，减少外出。\n");
        } else if (forecast.getType().contains("雪")) {
            advice.append("降雪易造成道路结冰（冰层厚度预计≥2mm），有滑倒、车辆打滑风险；户外作业需停止露天作业，设置警示标识。\n")
                    .append("【通勤规范】公共交通预计延误15 - 30分钟，驾车建议安装防滑链，保持≥100米车距，时速≤30km/h。\n")
                    .append("【健康防护】佩戴防风镜、厚手套，暴露皮肤每2小时涂抹防冻疮膏；避免长时间停留户外，预防低体温症。\n");
        } else if (forecast.getType().contains("晴")) {
            advice.append("晴好天气紫外线强度高（UVI≥6），长时间暴露易晒伤、眼损伤；户外作业每小时需补充500ml水分，佩戴遮阳装备。\n")
                    .append("【通勤规范】无特殊延误风险，但早高峰（7:30 - 9:00）、晚高峰（17:00 - 18:30）道路易拥堵。\n")
                    .append("【健康防护】外出涂抹SPF50 + 防晒霜，佩戴UV400级太阳镜；11:00 - 15:00高温时段避免户外作业。\n");
        } else {
            advice.append("特殊天气条件，建议实时关注气象预警；户外作业需配备应急物资，通勤优先选公共交通。\n");
        }

        advice.append("【官方提示】").append(forecast.getNotice());
        return advice.toString();
    }

}
